package com.hopedove.quanlitycheck.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hopedove.base.BaseActivity;
import com.hopedove.net.ErrResponse;
import com.hopedove.net.OkResponse;
import com.hopedove.net.domain.Communication;
import com.hopedove.quanlitycheck.R;
import com.hopedove.quanlitycheck.databinding.ActivityMain2Binding;
import com.hopedove.quanlitycheck.domain.net.GetInfo;
import com.hopedove.quanlitycheck.domain.net.SaveInfo;
import com.hopedove.quanlitycheck.entity.FgpzEntity;
import com.hopedove.quanlitycheck.utils.QualitySharedPrefUtil;
import com.hopedove.utils.ParseUtils;
import com.hopedove.utils.ToastUtil;
import com.hopedove.view.SimpleDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;


public class MainActivity2 extends BaseActivity {

    private String XM = "";
    private String JSMC = "";
    private final static String YES = "0";//明显、正确、合格
    private final static String NO = "1";//不明显、不合格、不正确

    FgpzEntity mFgpzEntity = null;
    FgpzEntity mOldFgpzEntity = null;

    String mUserBean;
    ActivityMain2Binding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMain2Binding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initDate();
        initViews();
        initEvents();
    }


    private void initDate() {
        XM = (String) QualitySharedPrefUtil.getValue(this, QualitySharedPrefUtil.XM, "");
        JSMC = (String) QualitySharedPrefUtil.getValue(this, QualitySharedPrefUtil.JSMC, "");
        mUserBean = (String) QualitySharedPrefUtil.getValue(this, QualitySharedPrefUtil.USERBEAN, "");
    }


    private void initViews() {
        binding.xmTv.setText(XM);

        switch (JSMC) {
            case "车间工艺员":
                visible(binding.gongyihuaxingAyout.root, binding.emptyLayout);
                gone(binding.carCheckLayout.root,
                        binding.qualityCheck.root,
                        binding.operationStatusLayout.root,
                        binding.verdictLayout.root);
                break;
            case "生产车间":
                gone(binding.gongyihuaxingAyout.root,
                        binding.qualityCheck.root,
                        binding.operationStatusLayout.root,
                        binding.verdictLayout.root);

                visible(binding.carCheckLayout.root,
                        binding.emptyLayout);
                break;
            case "检验员":
                gone(binding.gongyihuaxingAyout.root,
                        binding.carCheckLayout.root,
                        binding.operationStatusLayout.root,
                        binding.verdictLayout.root);
                visible(binding.qualityCheck.root,
                        binding.emptyLayout);
                break;
            case "保全工":
                visible(binding.gongyihuaxingAyout.root,
                        binding.carCheckLayout.root,
                        binding.qualityCheck.root,
                        binding.operationStatusLayout.root,
                        binding.verdictLayout.root);

                gone(binding.verdictLayout.root, binding.emptyLayout);
                setBaoquanAuthority();
                break;
            case "保全组长":
                visible(binding.gongyihuaxingAyout.root,
                        binding.carCheckLayout.root,
                        binding.qualityCheck.root,
                        binding.operationStatusLayout.root,
                        binding.verdictLayout.root);
                gone(binding.emptyLayout);
                setBaoquanAuthority();
                break;
        }

        /**控制输入数值内容大小**/
        judgeEditTextNumber(binding.gongyihuaxingAyout.gramEt);
        judgeEditTextNumber(binding.qualityCheck.weightEt);
        judgeEditTextNumber(binding.operationStatusLayout.speedEt);
    }


    /**
     * 设置保全工的操作权限
     */
    private void setBaoquanAuthority() {

        //原料
        binding.carCheckLayout.materialRadioBtn1.setClickable(false);
        binding.carCheckLayout.materialRadioBtn2.setClickable(false);
        //格局路数
        binding.carCheckLayout.patternRadioBtn1.setClickable(false);
        binding.carCheckLayout.patternRadioBtn2.setClickable(false);
        //针织三角
        binding.carCheckLayout.needleRadioBtn1.setClickable(false);
        binding.carCheckLayout.needleRadioBtn2.setClickable(false);
        //布面风格
        binding.carCheckLayout.clothStyleRadioBtn1.setClickable(false);
        binding.carCheckLayout.clothStyleRadioBtn2.setClickable(false);
    }


    private void initEvents() {
        setButtonsEvent();
        binding.baseInfoLayout.clothTktNoEt.setOnKeyListener((v, keyCode, event) -> {
            if (event != null
                    && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_UP) {
                String monadNo = binding.baseInfoLayout.clothTktNoEt.getText().toString().trim();
                queryByClothNo(monadNo);
                return true;
            }
            return false;
        });


        binding.baseInfoLayout.clothTktNoEt.addTextChangedListener(clothtktWatcher);
        //风格
        binding.gongyihuaxingAyout.styleRadioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            if (mFgpzEntity == null) return;
            if (i == R.id.styleRadioBtn1) {
                mFgpzEntity.setSTYLE(YES);
            } else {
                mFgpzEntity.setSTYLE(NO);
            }
        });
        //结构
        binding.gongyihuaxingAyout.structRadioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            if (mFgpzEntity == null) return;
            if (i == R.id.structRadioBtn1) {
                mFgpzEntity.setSTRUCT(YES);
            } else {
                mFgpzEntity.setSTRUCT(NO);
            }
        });
        //原料
        binding.carCheckLayout.materialRadioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            if (mFgpzEntity == null) return;
            if (i == R.id.materialRadioBtn1) {
                mFgpzEntity.setMATERIAL(YES);
            } else {
                mFgpzEntity.setMATERIAL(NO);
            }
        });
        //格局路数
        binding.carCheckLayout.patternRadioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            if (mFgpzEntity == null) return;
            if (i == R.id.patternRadioBtn1) {
                mFgpzEntity.setPATTERN(YES);
            } else {
                mFgpzEntity.setPATTERN(NO);
            }
        });
        //针织三角
        binding.carCheckLayout.needleRadioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            if (mFgpzEntity == null) return;
            if (i == R.id.needleRadioBtn1) {
                mFgpzEntity.setNEEDLE(YES);
            } else {
                mFgpzEntity.setNEEDLE(NO);
            }
        });

        //布面风格
        binding.carCheckLayout.clothStyleRadioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            if (mFgpzEntity == null) return;
            if (i == R.id.clothStyleRadioBtn1) {
                mFgpzEntity.setCLOTHSTYLE(YES);
            } else {
                mFgpzEntity.setCLOTHSTYLE(NO);
            }
        });

        //重量
        binding.qualityCheck.weightRadioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            if (mFgpzEntity == null) return;
            if (i == R.id.weightRadioBtn1) {
                mFgpzEntity.setWFLAG(YES);
            } else {
                mFgpzEntity.setWFLAG(NO);
            }
        });
        //羊角印
        binding.qualityCheck.hornRadioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            if (mFgpzEntity == null) return;
            if (i == R.id.hornRadioBtn1) {
                mFgpzEntity.setHORN(YES);
            } else {
                mFgpzEntity.setHORN(NO);
            }
        });
        //细皱纹
        binding.qualityCheck.wrinkleRadioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            if (mFgpzEntity == null) return;
            if (i == R.id.wrinkleRadioBtn1) {
                mFgpzEntity.setWRINKLE(YES);
            } else {
                mFgpzEntity.setWRINKLE(NO);
            }
        });
        //车速是否正常
        binding.operationStatusLayout.speedRadioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            if (mFgpzEntity == null) return;
            if (i == R.id.speedRadioBtn1) {
                mFgpzEntity.setSFLAG(YES);
            } else {
                mFgpzEntity.setSFLAG(NO);
            }
        });
        //结论
        binding.verdictLayout.verdictRadioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            if (mFgpzEntity == null) return;
            if (i == R.id.verdictRadioBtn1) {
                mFgpzEntity.setVERDICT(YES);
            } else {
                mFgpzEntity.setVERDICT(NO);
            }
        });


    }

    TextWatcher clothtktWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            mFgpzEntity = null;
        }
    };

    private void setData() {

        if (mFgpzEntity == null) {

            return;
        }
        binding.baseInfoLayout.clothTktNoEt.removeTextChangedListener(clothtktWatcher);
        /*******************基础信息*******************/
        binding.baseInfoLayout.clothTktNoEt.setText(mFgpzEntity.getCLOTHTKTNO());
        binding.baseInfoLayout.workshopTv.setText(mFgpzEntity.getWORKSHOP());//车间
        binding.baseInfoLayout.machineNoTv.setText(mFgpzEntity.getMACHINENO());//车号
        binding.baseInfoLayout.bqNoTv.setText(mFgpzEntity.getBQNAME());//保全工
        binding.baseInfoLayout.taskLxTv.setText(mFgpzEntity.getTASKLX());//任务类型
        binding.baseInfoLayout.clothNoTv.setText(mFgpzEntity.getCLOTHNO());//布号
        binding.baseInfoLayout.pbmcTv.setText(mFgpzEntity.getPBMC());//品种
        /*******************工艺花形*******************/
        binding.gongyihuaxingAyout.loopLengthTv.setText(mFgpzEntity.getLOOPLENGTH());//线圈长度
        binding.gongyihuaxingAyout.gramEt.setText(mFgpzEntity.getGRAM());//克重
        binding.gongyihuaxingAyout.densityEt.setText(mFgpzEntity.getDENSITY());//密度

        setRadiobtnStatus(binding.gongyihuaxingAyout.styleRadioGroup, mFgpzEntity.getSTYLE());//风格
        setRadiobtnStatus(binding.gongyihuaxingAyout.structRadioGroup, mFgpzEntity.getSTRUCT());//结构

        /*******************车况检查*******************/
        setRadiobtnStatus(binding.carCheckLayout.materialRadioGroup, mFgpzEntity.getMATERIAL());//原料
        setRadiobtnStatus(binding.carCheckLayout.patternRadioGroup, mFgpzEntity.getPATTERN());//格局路数
        setRadiobtnStatus(binding.carCheckLayout.needleRadioGroup, mFgpzEntity.getNEEDLE());//针织三角
        setRadiobtnStatus(binding.carCheckLayout.clothStyleRadioGroup, mFgpzEntity.getCLOTHSTYLE());//布面风格
        /*******************质量检查*******************/
        binding.qualityCheck.weightEt.setText(mFgpzEntity.getWEIGHT());//重量
        binding.qualityCheck.weightEt.setFocusable(true);
        setRadiobtnStatus(binding.qualityCheck.weightRadioGroup, mFgpzEntity.getWFLAG());//重量（检查项）
        setEditTextStatus(binding.qualityCheck.weightEt, mFgpzEntity.getWFLAG());//重量  (文本)
        setRadiobtnStatus(binding.qualityCheck.hornRadioGroup, mFgpzEntity.getHORN());//羊角印
        setRadiobtnStatus(binding.qualityCheck.wrinkleRadioGroup, mFgpzEntity.getWRINKLE());
        /*******************运转情况*******************/
        binding.operationStatusLayout.speedEt.setText(mFgpzEntity.getSPEED());//速度
        binding.operationStatusLayout.speedEt.setFocusable(true);
        setRadiobtnStatus(binding.operationStatusLayout.speedRadioGroup, mFgpzEntity.getSFLAG());//速度
        setEditTextStatus(binding.operationStatusLayout.speedEt, mFgpzEntity.getSFLAG());//速度 (文本)
        /*******************结论*******************/
        setRadiobtnStatus(binding.verdictLayout.verdictRadioGroup, mFgpzEntity.getVERDICT());
        if ("保全工".equals(JSMC)) {
            //最后在设置一下保全工的权限
            setBaoquanAuthority();
        }
        if ("保全组长".equals(JSMC)) {
            //最后在设置一下保全工的权限
            setBaoquanAuthority();
        }
        binding.baseInfoLayout.clothTktNoEt.addTextChangedListener(clothtktWatcher);
    }


    private void setRadiobtnStatus(RadioGroup radioGroup, String status) {
        RadioButton btn1 = (RadioButton) radioGroup.getChildAt(0);
        RadioButton btn2 = (RadioButton) radioGroup.getChildAt(1);
        btn1.setClickable(true);
        btn2.setClickable(true);
        if (YES.equals(status)) {
            btn1.setChecked(true);
            if (!"0".equals(mFgpzEntity.getDATASOURCE())) {
                //如果检查项为0,且datasource不为0的时候，，则设置为不可编辑
                if (!(radioGroup.getId() == R.id.verdictRadioGroup)) {//除了最后一项不要设置
                    btn1.setClickable(false);
                    btn2.setClickable(false);
                }
            }
        } else if (NO.equals(status)) {
            btn2.setChecked(true);
        }
    }

    private void setEditTextStatus(EditText editText, String status) {


        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);//必须加这个，不然还是无法获取焦点
        if (YES.equals(status)) {
            if (!"0".equals(mFgpzEntity.getDATASOURCE())) {
                //如果检查项为0,且 dataSource 不为0的时候，，则设置为不可编辑
                editText.setFocusable(false);
            }
        }

    }

    /**
     * 控制 editText 输入格式    最大9999，小数点后最多一位
     */
    private void judgeEditTextNumber(EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {


            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {


                String temp = editable.toString();
                int posDot = temp.indexOf(".");//返回指定字符在此字符串中第一次出现处的索引
                int index = editText.getSelectionStart();//获取光标位置

                if (posDot < 0) {//不包含小数点
                    if (temp.length() <= 4) {
                        return;//小于四位数直接返回
                    } else {
                        editable.delete(index - 1, index);//删除光标前的字符
                        return;
                    }
                }
                if (posDot > 4) {//小数点前大于4位数就删除光标前一位
                    editable.delete(index - 1, index);//删除光标前的字符
                    return;
                }
                if (temp.length() - posDot - 1 > 1)//如果包含小数点   控制小数点后面最多一位
                {
                    editable.delete(index - 1, index);//删除光标前的字符
                    return;
                }


            }
        });
    }


    private void resetData() {


        /*******************基础信息*******************/

        binding.baseInfoLayout.workshopTv.setText("");//车间
        binding.baseInfoLayout.machineNoTv.setText("");//车号
        binding.baseInfoLayout.bqNoTv.setText("");//保全工
        binding.baseInfoLayout.taskLxTv.setText("");//任务类型
        binding.baseInfoLayout.clothNoTv.setText("");//布号
        binding.baseInfoLayout.pbmcTv.setText("");//品种
        /*******************工艺花形*******************/
        binding.gongyihuaxingAyout.loopLengthTv.setText("");//线圈长度
        binding.gongyihuaxingAyout.gramEt.setText("");//克重
        binding.gongyihuaxingAyout.densityEt.setText("");//密度
        //风格
        binding.gongyihuaxingAyout.styleRadioGroup.clearCheck();

        //结构
        binding.gongyihuaxingAyout.structRadioGroup.clearCheck();

        /*******************车况检查*******************/
        //原料
        binding.carCheckLayout.materialRadioGroup.clearCheck();

        //格局路数
        binding.carCheckLayout.patternRadioGroup.clearCheck();

        //针织三角
        binding.carCheckLayout.needleRadioGroup.clearCheck();
        binding.carCheckLayout.clothStyleRadioGroup.clearCheck();

        /*******************质量检查*******************/
        binding.qualityCheck.weightEt.setText("");//重量
        binding.qualityCheck.weightRadioGroup.clearCheck();
        binding.qualityCheck.hornRadioGroup.clearCheck();
        binding.qualityCheck.wrinkleRadioGroup.clearCheck();
        /*******************运转情况*******************/
        binding.operationStatusLayout.speedEt.setText("");//速度
        binding.operationStatusLayout.speedRadioGroup.clearCheck();
        /*******************结论*******************/
        binding.verdictLayout.verdictRadioGroup.clearCheck();
        mFgpzEntity = null;
    }


    private void startCommit() {

        if (mFgpzEntity == null) {
            Toast.makeText(this, "请先查询三联单号再保存提交！", Toast.LENGTH_SHORT).show();
            return;
        }
        switch (JSMC) {
            case "车间工艺员":

                break;
            case "生产车间班长":

                break;
            case "检验员":

                break;
            case "挡车工":

                break;
            case "保全工":

                break;
        }
        /*******************基础信息*******************/
        /*******************工艺花形*******************/
        mFgpzEntity.setGRAM(binding.gongyihuaxingAyout.gramEt.getText().toString().trim());//克重
        mFgpzEntity.setDENSITY(binding.gongyihuaxingAyout.densityEt.getText().toString().trim());//密度
        /*******************车况检查*******************/
        /*******************质量检查*******************/
        mFgpzEntity.setWEIGHT(binding.qualityCheck.weightEt.getText().toString().trim()); //重量
        /*******************运转情况*******************/
        mFgpzEntity.setSPEED(binding.operationStatusLayout.speedEt.getText().toString().trim());//速度
        /*******************结论*******************/
        commit(mOldFgpzEntity, mFgpzEntity);
    }


    /**
     * 查询已经保存的数据
     *
     * @param monadNo
     */
    private void queryByClothNo(String monadNo) {
        showWait();
        GetInfo getInfo = new GetInfo(monadNo);
        Communication.asyncRequest(getInfo, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    JSONArray data = jsonObj.optJSONArray("DATA");
                    if (data != null) {
                        Gson gson = new Gson();
                        List<FgpzEntity> clothList = gson.fromJson(data.toString(), new TypeToken<List<FgpzEntity>>() {
                        }.getType());
                        final String[] array = new String[clothList.size()];
                        for (int i = 0; i < clothList.size(); i++) {
                            array[i] = "三联号：" + clothList.get(i).getCLOTHTKTNO() + "，车号：" + clothList.get(i).getCLOTHNO();
                        }


                        new MaterialDialog.Builder(MainActivity2.this)
                                .title("选择三联号")
                                .items(array)
                                .itemsColor(getColorCompat(R.color.black))
                                .itemsCallbackSingleChoice(-1, (dialog, view, which, text) -> {
                                    FgpzEntity fgpzEntity = clothList.get(which);

                                    if (fgpzEntity != null) {
                                        resetData();//先重置页面和数据
                                        mFgpzEntity = fgpzEntity;
                                        try {
                                            mOldFgpzEntity = mFgpzEntity.clone();
                                        } catch (CloneNotSupportedException e) {
                                            ToastUtil.longToast(this, e.toString());
                                        }
                                        setData();
                                    }
                                    return true;
                                })
                                .show();
                    } else {
                        JSONObject data2 = jsonObj.optJSONObject("DATA");
                        if (data2 != null) {
                            FgpzEntity fgpzEntity = ParseUtils.parse(data2.toString(), FgpzEntity.class);
                            if (fgpzEntity != null) {
                                resetData();//先重置页面和数据
                                mFgpzEntity = fgpzEntity;
                                mOldFgpzEntity = mFgpzEntity.clone();
                                setData();
                            }
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.longToast(this, "数据解析异常");
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, ((ErrResponse) r).getErrText());
            }
        });
    }


    /**
     * 保存信息
     */
    private void commit(FgpzEntity oldFgpzEntity, FgpzEntity fgpzEntity) {
        showWait();

        SaveInfo saveInfo = new SaveInfo(mUserBean, oldFgpzEntity, fgpzEntity);
        Communication.asyncRequest(saveInfo, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    String msg = jsonObj.optString("MSG_INFO");
                    binding.baseInfoLayout.clothTktNoEt.setText("");
                    resetData();

                    if (TextUtils.isEmpty(msg)) {
                        SimpleDialog.show(this, "提交成功");
                    } else {
                        SimpleDialog.show(this, msg);
                    }
                } catch (JSONException e) {
                    SimpleDialog.show(this, "提交失败");
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, ((ErrResponse) r).getErrText());
            }
        });
    }


    private void setButtonsEvent() {
        binding.okBtn.setOnClickListener(__ -> startCommit());
        binding.cancelBtn.setOnClickListener(__ -> finish());
    }


    private static void gone(View... v) {
        for (View view : v) {
            view.setVisibility(View.GONE);
        }
    }

    private static void visible(View... v) {
        for (View view : v) {
            view.setVisibility(View.VISIBLE);
        }
    }
}
